[conflicted] Will prefer haven::is.labelled over any other package.
[conflicted] Will prefer dplyr::filter over any other package.
Lab 01
Agenda
- Learning to Code
- R & RStudio Workflow
- Getting Started
Learning objectives
By the end of the lab, you will be able to …
- setup a reproducible workflow using R and RStudio
- familiarize yourself with a dataset using R and RStudio
- create a reproducible report using Quarto
Learning to Code
Technology is fun!
You’re not just learning the statistical concepts in this course, but how to produce the statistics. Analyzing data requires learning to use new technology.
Learning statistical software to analyze data can be really fun. You get to learn about real world social problems!
Technology is challenging!
It can be frustrating.
When it feels like the technology is preventing you from getting to the course content, take a deep breath, and remember that building your technology skills is part of this course.
Replication using technology requires researchers to sometimes use unfamiliar software, working on devices with unique environments and settings.
There’s even a bingo card of common errors (i.e. bugs) that new statistical programmers will expect to experience.
Why am I making you learn something so frustrating?
Calculating the statistics by hand quickly gets cumbersome, time consuming, and difficult.
Good social science is built on replication.
You’ll learn the statistical techniques using small sample sizes, but to really understand the social world, datasets typically have 100s, 1,000s, even 100,000s of values.
It is impractical, and more prone to errors, for scientists to replicate research by hand. Replication of statistical procedures helps catch minor coding errors, highlights unusual decisions made by researchers, inappropriate statistical techniques, and corrupted data.
Grappling
Learning to use statistical software necessitates grappling.
Grappling implies trying even before you fail the first time.
It’s thinking, “First, I’ll work with it independently. Okay, I’m really not understanding it. Let me go back to my notes. Okay, I have solved for the first part of it. Now I have the second part of it. Okay, I got the question wrong; let me try again. Maybe I can ask my peer now.”
Grappling is working hard to make sure you understand the problem fully, and then using every resource at your fingertips to solve it.”
In this course, this means you’ll put your active learning skills to use. You, not your professor or TA, will work through encountered problems. You, of course, will be supported and coached through the entire process. Working with statistical software will become easier as you build your skills in problem-solving errors. Unfortunately, it gets increasingly difficult if you rely on others to solve the issue, as the errors stack-up.
Most statistical analyses happen not because the person is a math genius, but because they persisted through the minefield of technical issues by being excellent problem-solvers.
Get comfortable with making mistakes right now. Your code is not expected to be perfect the first time. Remember, identifying and fixing errors in your own code is such an inherent part of the process, there’s even a name for it: debugging.
Coding is mostly Googling
It is a misconception that the best statistical analysts sit down at their computers and type code from memory.
Much of process of coding is copying code from somewhere else and modifying it to fit your particular situation.
Learning to analyze data with software requires a lot of practice and attention to detail. It also requires a lot of time searching the internet for help. Learning to identify the right words and phrases in a Google search is part of building your coding skills.
When you get stuck…
…there are many options to get unstuck:
- Review the slides. Pay very close attention to small details.
- Try something else to see if you get a new error.
- Use Google to search for possible answers or new explanations.
- Watch a help video on YouTube on the topic.
- Re-start your web-browser or device.
- Try another web-browser or device.
- Ask a peer. Or an advanced student.
- Start or join a weekly study group.
- Post the question on the class discussion board.
- Email your TA
When none of these strategies fix the issue, it is time to ask for help.
Help in this class
Before requesting an individual meeting with a TA:
- Spend a sufficient amount of time working on it on your own.
- Ask two of your peers.
- Post the question on the class discussion board.
When emailing:
- Explain what troubleshooting steps you’ve already taken.
- Report who you’ve already asked for help.
If none of these solve your problem, draft an email to your TA, with detailed notes about the problem and the troubleshooting steps you’ve already taken. You might be surprised how often even writing the problem out in detail helps you find the answer on your own. Send your email if you still need assistance.
Create a trail!
Use replication principles when asking for help. The best quantitative researchers produce a trail for their code so that future researchers can replicate their analysis.
Create a reproducible example
Goal: Make someone else to feel your pain!
- Assume others know nothing about your issue.
- Describe your steps to create the problem so that someone else can replicate it.
- This means clearly describing the issue and the steps you’ve already taken to solve it.
Good etiquette
Search for answers before posting your question.
Let me google that for you. 🙄
Describe the problem.
“It doesn’t work” isn’t descriptive enough.
Describe your environment.
What operating system are you using? Which R version? What packages? Dataset?
Describe the solution.
Confirm if a solution offered works. Or, if you solve it on your own, post how you solved it.
Try to stay focused on being in the process, not the outcome.
R & RStudio Workflow
Replication
The guiding principle for workflow.
A workflow of data analysis is a process for managing all aspects of data analysis.
Planning, documenting, and organizing your work; cleaning the data; creating, renaming, and verifying variables; performing and presenting statistical analyses; producing replicable results; and archiving what you have done are all integral parts of your workflow.
Source: (Long 2008)
Steps in a workflow
| Set up | Systematic organization of the project and project files. |
| Familiarize self with data | Skipping takes more time in the long run. |
| Process data | Takes the MOST time. |
| Running analyses | What people THINK takes the most time. |
| Presenting results | What people (wrongly) think does not take time. |
File types
There are many file types, but these are key to an R & RStudio workflow (and likely new to you):
| Extension | Description |
|---|---|
| .Rproj | RStudio project file (keeps project settings). |
| .R | R scripts store a sequence of R commands (code) that can be run all at once or line by line. |
| .qmd | Quarto Markdown creates reproducible documents that contain a combination of text, code, and output. |
| .Rdata (or sometimes .rda) | These store and load R objects—like data frames. |
File names
should be:
- machine-readable
- human-readable
- play well with default-ordering
RStudio Projects
Create a RStudio project for each data analysis project.
It supports an organized and reproducible workflow, cleanly separated from all other projects that you are working on. Everything you need in one place:
- local data files to load into RStudio.
- scripts to edit or run in bits or as a whole.
- Save your outputs (plots and cleaned data).
Filepaths
Adopting a project-based workflow avoids changing file paths.
ABSOLUTE FILE PATHS
Department of Sociology
Unit 17100, 17th Floor, Ontario Power Building
700 University Ave., Toronto, ON M5G 1Z5
C:\Users\Pepin\GitHub\SOC6302\scripts
RELATIVE FILE PATHS
Take the left side elevators to the 17th floor.
Go through the double doors and a take a right.
First door on your left.
here(scripts)
Create a RStudio Project
To create a new project in RStudio, click: File > New Project.
In the New Project wizard that pops up, select: New Directory, then New Project.
Name the project “SOC6302” and click: Create Project.
This will launch you into a new RStudio Project inside a new folder called “SOC6302”.
R-script
Open RStudio, then click the dropdown arrow next to the “New File icon,” and then “R script.”
Alternatively, hold down “Ctrl” + “Shift” + “N.”
An R-script is a file that will contain the documentation of the code of what you tell R to do.
Panes
When your script is open, you’ll see four key regions or “panes” in the interface:
Source pane: where you can edit and save R scripts or author computational documents like Quarto and R Markdown.
Console pane: is used to write short interactive R commands.
Environment pane: displays temporary R objects created during that R session.
Output pane: displays the plots, tables, or HTML outputs of executed code along with files saved to disk.
Console pane: best for exploring.
Source pane: best for documenting.
Quarto
Quarto: The tool you’ll use to create reproducible computational documents. Every piece of assignment you hand in will be a Quarto document.
You are likely familiar with word processors like MS Word or Google Docs. We will not be using these in this class. Instead, the words you would write in such a document, as well as your R code, will go into a Quarto document. You will render the document (more on what this means later) to get a document out that has your words, code, and the output of that code. Everything in one place, beautifully formatted!
RScript vs Quarto
RScript
great for learning, exploring and tinkering.
rerun it without attention to formatting or markdown.
Quarto
great for communicating analysis and results
combines narrative explanation with code output (results.
Documentation
In .R scripts and Quarto, you can document your code. Err on the side of over documentation. Your future self will thank you.
Blank slate
Clear the memory at every restart of RStudio by turning off the automatic saving of your workspace and .Rdata files with you quit RStudio. This is important for reproducibility, debugging, and avoiding littering your computer with unnecessary files.
Set this via:
- Tools > Global Options.
- Uncheck “Restore .RData into Workspace at Startup”.
- Choose “Never” on the “Save workspace to .RData on exit”.
- Click “Apply” and “OK”.
Packages
R comes with basic tools, but packages extend the capabilities of base R (what you already installed). An R package is like a toolbox: a collection of functions, data, and documentation that help you do specific tasks using R.
You’ll install each package (only once per system):
install.packages("tidyverse")Warning: package 'tidyverse' is in use and will not be installed
You’ll load each package (every time you use it):
library(tidyverse)Comprehensive R Archive Network (CRAN)
CRAN is like an App Store for R. It hosts R packages, documentation, and source code contributed by users worldwide. It is mediated (e.g., quality control), making it incredibly reliable.
R users can easily install, update, and share R packages using install.packages().
Support
Some help videos and further explanation:
Getting Started
Open RStudio
Open your SOC6302 Project
(See slide on Creating RStudio Projects)
Download and open your first code-along
Packages
We’ll use the following packages:
here()(relative file paths)tidyverse()(data wrangling)gssr()(U.S. General Social Survey data)gssrdoc()(GSS documentation)
Install here() and tidyverse()
Let’s first install the two packages that are available on CRAN.
Copy and paste the following code into your Console pane. Then hit enter.
install.packages("here")Then do the same to install the tidyverse package.
install.packages("tidyverse")Install gssr() and gssrdoc()
# Install 'gssr' from 'ropensci' universe
install.packages('gssr', repos =
c('https://kjhealy.r-universe.dev', 'https://cloud.r-project.org'))Warning: package 'gssr' is in use and will not be installed
# Also recommended: install 'gssrdoc' as well
install.packages('gssrdoc', repos =
c('https://kjhealy.r-universe.dev', 'https://cloud.r-project.org'))Installing package into 'C:/R/library'
(as 'lib' is unspecified)
package 'gssrdoc' successfully unpacked and MD5 sums checked
The downloaded binary packages are in
C:\Users\Joanna\AppData\Local\Temp\RtmpEjnurk\downloaded_packages
Load the packages
library(here)here() starts at C:/Users/Joanna/Documents/GitHub/Stats-for-Sociologists
library(tidyverse)
library(gssr)
library(gssrdoc)Set up your project structure
here()
here:here() # set the file path to the root of the project
Environment
session_info() # software documentation
YAML Ain’t Markup Language